<template>
  <!-- 新增联系人界面 -->
  <div class="contact-add">
    <!-- navbar标题栏 -->
    <van-nav-bar title="编辑联系人" left-text="返回" left-arrow @click-left="goBack" />
    <!-- 联系人编辑框 -->
    <van-contact-edit
      is-edit
      show-set-default
      :contact-info="editingContact"
      set-default-label="设为默认联系人"
      @save="onSave"
      :tel-validator="validatorTel"
      @delete="onDelete"
    />
  </div>
</template>

<script>
export default {
  props: ["id"],
  data() {
    return {
      editingContact: {}
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    /**
     * 根据联系人id获取联系人信息
     */
    loadData() {
      this.http
        .get(`${this.$api.getContact}/${this.id}`)
        .then(res => res.data)
        .then(res => {
          if (res.code == 200) {
            this.editingContact = res?.data[0];
            // 设置默认按钮选中
            if (this.editingContact.isDefault == 1) {
              this.$set(this.editingContact, "isDefault", true);
            }
          } else {
            this.$msg.fail(res.msg);
            this.$router.back();
          }
        });
    },
    /**
     * 手机号格式校验
     */
    validatorTel(tel) {
      return /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
        tel
      );
    },
    /**
     * 返回上一页
     */
    goBack() {
      this.$router.back();
    },
    /**
     * 保存联系人
     */
    onSave(contactInfo) {
      // 获取联系人数据
      let { name, tel, isDefault } = contactInfo;
      if (isDefault) {
        isDefault = 1;
      } else {
        isDefault = 0;
      }

      this.http
        .put(`${this.$api.editContact}`, { id: this.id, name, tel, isDefault })
        .then(res => res.data)
        .then(res => {
          if (res.code == 200) {
            this.$msg.success(res.msg);
            // 新增成功，返回
            setTimeout(() => {
              this.$router.back();
            }, 2000);
          } else {
            this.$msg.fail(res.msg);
          }
        });
      // this.$msg.fail("保存");
    },
    /**
     * 删除联系人
     */
    onDelete(contact) {
      this.http
        .delete(`${this.$api.deleteContact}/${contact.id}`)
        .then(res => res.data)
        .then(res => {
          if (res.code == 200) {
            this.$msg.success(res.msg);
            // 新增成功，返回
            setTimeout(() => {
              this.$router.back();
            }, 2000);
          } else {
            this.$msg.fail(res.msg);
          }
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.van-button--danger {
  color: #fff;
  background-color: #f8e176 !important;
  border: 1px solid #f8e176 !important;
}
</style>